<?php


namespace Frieza\Modules\Search\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\AdmSearchKeyword\SearchAllTag as mSearchAllTag;
use Doraemon\pockets\constInterface\LinkConf;
use Doraemon\tools\LinkFormat;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


/**
 * 搜索预置词
 * Class PresetKeywordController
 * @package Frieza\Modules\Search\Controllers
 */
class SearchAllTagController extends Controller
{
    const PAGE_SIZE = 20;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $result = mSearchAllTag::selectByWhere(['operate_status' => mSearchAllTag::STATUS_NORMAL, 'ORDER' => ['sort' => 'ASC', 'id' => 'DESC']]);
        $list = [];
        foreach ($result as $row) {
            $linkArr = LinkFormat::generateLink($row['link_type'], $row['link_params']);
            $row['link'] = $linkArr[LinkConf::TEMPLATE_TYPE_APP];
            $row['is_highlight'] = $row['is_highlight'] ? '是' : '否';
            $list[] = $row;
        }
        $gridModel = new pGridDataModel($list);
        $listGrid = Admin::grid($gridModel, function (Grid $grid) {
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableFilter();
            $grid->column('id')->sort();
            $grid->column('tag_name', '标签名称')->width(150);
            $grid->column('start_time', '开始时间')->width(150);
            $grid->column('end_time', '结束时间')->width(150);
            $grid->column('link', '链接')->width(150);
            $grid->column('is_highlight', '是否高亮')->width(150);
            $grid->column('remarks', '运营备注');
            $grid->column('admin_id', '管理员')->display(function () {
                if (!$this->admin_id) {
                    return '暂无';
                } else {
                    return Admin::user()->find($this->admin_id)->name;
                }
            });
            $grid->disablePagination();
        });
        $list = $listGrid->render();
        return $content
            ->header('大家都在搜列表')
            ->breadcrumb(
                ['text' => '大家都在搜列表']
            )
            ->body($list);
    }

    public function create(Request $request, Content $content, $id = 0)
    {
        $header = $id ? '编辑搜索词' : '添加搜索词';
        $info = [];
        if ($id) {
            $info = mSearchAllTag::getByWhere(['id' => $id]);
            $info['link'] = [
                'link_type' => $info['link_type'],
                'link_params' => $info['link_params']
            ];
        }
        $form = new Form($info);
        if ($id) {
            $form->text('id', 'id')->readonly();
        }
        $form->text('tag_name', '标签名称')->required();
        $form->datetime('start_time', '开始时间')->required();
        $form->datetime('end_time', '结束时间')->required();
        $form->select('is_highlight', '是否高亮')
            ->options([0 => '否', '是'])->default(0);
        $form->text('remarks', '运营备注');
        $form->linkSelect('link', '跳转链接');

        $form->action('/admin/search/keyword/save');

        return $content->header($header)->breadcrumb(
            ['text' => '大家都在搜列表', 'url' => url('admin/search/keyword/index')],
            ['text' => $header])
            ->row($form->render());
    }

    public function save(Request $request, Content $content)
    {
        try {
            $id = $request->input("id", 0);
            $tagName = $request->input("tag_name", "");
            $startTime = $request->input("start_time", "");
            $endTime = $request->input("end_time", "");
            $isHighLight = $request->input("is_highlight", 0);
            $remark = $request->input("remarks", '');
            $linkType = $request->input('link_type', '');
            $linkParams = $request->input("link_params", "");
            $linkParams = $linkParams ? json_encode($linkParams, JSON_UNESCAPED_UNICODE) : '';
            $data = [
                'tag_name' => $tagName,
                'is_highlight' => $isHighLight,
                'start_time' => $startTime,
                'end_time' => $endTime,
                'remarks' => $remark,
                'link_type' => $linkType,
                'link_params' => $linkParams,
                'admin_id' => Admin::user()->id,
                'addtime' => date('Y-m-d H:i:s'),
                'edittime' => date('Y-m-d H:i:s')
            ];
            if ($id) {
                $result = mSearchAllTag::updateData($data, ['id' => $id]);
            } else {
                $result = mSearchAllTag::insertData($data);
            }
            if ($result) {
                return redirect(url('/admin/search/keyword/index'))->with(compact('success'));
            } else {
                $error = new MessageBag([
                    'title' => '操作失败'
                ]);
                return back()->withInput()->with(compact('error'));
            }
        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => '操作失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

    public function sort(Request $request)
    {
        $sortInfo = $request->input('sort');
        foreach ($sortInfo as $id => $sort) {
            mSearchAllTag::updateData(['sort' => $sort], ['id' => $id]);
        }
    }

    public function del(Request $request, Content $content, $id)
    {
        if ($id) {
            mSearchAllTag::updateData(['operate_status' => mSearchAllTag::STATUS_DELETE], ['id' => $id]);
        }
        return redirect(url('/admin/search/keyword/index'))->with(compact('success'));
    }

}